using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security.Principal;
using System.Reflection;

namespace DataLoad.iContact.WinClient
{
    public partial class frmExceptions : Form
    {
        public frmExceptions()
        {
            InitializeComponent();
        }

        public static DialogResult ShowError(Exception exc)
        {
            using (frmExceptions frm = new frmExceptions())
            {
                frm.edtReport.Text = frm.GenerateReport(exc);
                frm.edtReport.SelectAll();

                return frm.ShowDialog();
            }
        }

        private string GenerateReport(Exception e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendFormat("Version {0}{1}", Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.NewLine);
                sb.AppendFormat("OS Version: {0}{1}", Environment.OSVersion.VersionString, Environment.NewLine);
                sb.AppendFormat(".NET Framework: {0}{1}", Environment.Version.ToString(), Environment.NewLine);
                sb.AppendFormat("Is User interactive: {0}{1}", Environment.UserInteractive.ToString(), Environment.NewLine);
                sb.AppendFormat("Exception: {0}{1}", e.Message, Environment.NewLine);
                sb.AppendFormat("Stack trace: {0}{1}", e.StackTrace, Environment.NewLine);

                WindowsIdentity wi = WindowsIdentity.GetCurrent();
                WindowsPrincipal wp = new WindowsPrincipal(wi);
                sb.AppendFormat("Admin rights: {0}{1}", wp.IsInRole(WindowsBuiltInRole.Administrator).ToString(), Environment.NewLine);

                sb.AppendLine("Processes:");
                foreach (Process p in Process.GetProcesses())
                {
                    sb.AppendLine(p.ProcessName);
                }

                return sb.ToString();
            }
            catch (Exception exc)
            {
                return "Unable to generate the report: " + exc.Message;
            }
        }

        private void lblEmail_Click(object sender, EventArgs e)
        {
            Process.Start("mailto:support@dataload.com");
        }
    }
}